const { verify } = require('jsonwebtoken')

function getUserId(ctx) {
  // console.log(ctx.request.headers)
  const Authorization = ctx.request.get('Authorization')
  if (Authorization) {
    const token = Authorization.replace('Bearer ', '')
    const { userId } = verify(token, process.env.APP_SECRET)
    console.log(token, userId, process.env.APP_SECRET)
    return userId
  }

  throw new AuthError()
}

const isAdmin = async ctx => {
  const id = getUserId(ctx)
  if (id !== 'cjn9yc99i00730713az8fljej') {
    throw new PremissionError()
  }

  return id

  /* const user = await ctx.db.user({ id })

  if (!user || user.role !== 'ADMIN') {
    return new PremissionError()
  } */
}

const getOpenid = async code => {
  if (code) {
    const response = await fetch(
      `${process.env.CODE_2_SESSION}?appid=${process.env.WAPP_ID}&secret=${
        process.env.WAPP_SECRET
      }&js_code=${code}&grant_type=authorization_code`
    )
    const data = await response.json()
    console.log(code, data)
    return data.openid
  }
  return null
}

class AuthError extends Error {
  constructor() {
    super('Not authorized')
  }
}

class PremissionError extends Error {
  constructor() {
    super('Not premission')
  }
}

class SignupError extends Error {
  constructor(msg) {
    super(msg || 'Signup params error')
  }
}

module.exports = {
  getUserId,
  isAdmin,
  getOpenid,
  AuthError,
  PremissionError,
  SignupError
}
